<?php

namespace App\Services\Search;

use App\admin\Service\OA;
use App\Jobs\Fun;
use App\Models\Admin\JobModel;
use App\Models\Admin\StaffOptionModel;
use App\Models\JobsCompanysModel;
use App\Models\User\UsergongchangModel;
use App\Models\User\UserGongsiModel;
use App\Models\User\UserModel;
use App\Models\UserStaffModel;
use App\Repositories\Admin\CompanyRepository;
use App\Repositories\Admin\JobCompanyRepository;
use App\Repositories\Admin\JobRepository;
use App\Repositories\Admin\OrderBaleRepository;
use App\Repositories\Admin\SearchRepository;
use App\Repositories\Admin\SearchLogRepository;
use App\Repositories\Admin\StaffRepository;
use App\Repositories\Admin\UserRepository as User;
use App\Repositories\UserRepository;

use App\Models\Admin\CompanyModel;
use App\Models\AreaModel;
use App\Models\Admin\CategoryModel;
use App\Models\Admin\StaffModel;
use App\Models\Admin\OrderBaleModel;

class SearchService
{
    public function __construct()
    {

    }

    /**
     * 手机版搜索
     * 参数: word:表示关键词 type:gs,gc,gr 分别表示公司,工厂,个人
     */
    public function getFind($word, $typ)
    {
        if ($typ == 'gs') {
            return $this->getfindGs($word);
        } elseif ($typ == 'gc') {
            return $this->getfindGc($word);
        } elseif ($typ == 'gr') {
            return $this->getfindGr($word);
        } elseif ($typ == 'hd') {
            return $this->getfindHd($word);
        } elseif ($typ == 'gw') {
            return $this->getfindGw($word);
        } else {
            OA::Json(1, '参数错误');
        }
    }

    private $MaxCount = 100;

    private function getfindGs($word)
    {

        $jieguolist = [];
        $word = '%' . $word . '%';
        $titlemodel = UserGongsiModel::getModel()
            ->whereRaw('legal_name LIKE ? OR com_name LIKE ?', [$word, $word])
            ->where([
                'visible' => 1
            ])->select([
                'id', 'uid', 'legal_name',
                'com_name', 'detail'
            ])
          //  ->orderBy('id', 'desc')
            ->get();
        $titlelist = [];
        if ($titlemodel) {
            $titlelist = $titlemodel->toArray();
        }
        foreach ($titlelist as $vo) {
            $user = UserModel::getinfo($vo['uid']);
            $jieguolist[] = [
                'uid' => $vo['uid'],
                'user_name' => $user['name'],
                'user_head' => $user['head'],
                'com_name' => $vo['com_name'],
                'detail' => Fun::shenglue($vo['detail'], 64),
            ];
        }
        return $jieguolist;

    }

    private function getfindGc($word)
    {
         $jieguolist = [];
        $word = '%' . $word . '%';
        $titlemodel = \App\Models\User\UsergongchangModel::getModel()
            ->whereRaw('legal_name LIKE ? OR com_name LIKE ?', [$word, $word])
            ->where([
                'visible' => 1
            ])->select([
                'id', 'uid', 'legal_name',
                'com_name', 'detail'
            ])
          //  ->orderBy('id', 'desc')
            ->get();
        $titlelist = [];
        if ($titlemodel) {
            $titlelist = $titlemodel->toArray();
        }
        foreach ($titlelist as $vo) {
            $user = UserModel::getinfo($vo['uid']);
            $jieguolist[] = [
                'uid' => $vo['uid'],
                'user_name' => $user['name'],
                'user_head' => $user['head'],
                'com_name' => $vo['com_name'],
                'detail' => Fun::shenglue($vo['detail'], 64),
            ];
        }
        return $jieguolist;
    }

    private function getfindGr($word)
    {
        $titleList = Search_grModel::where('name', 'LIKE', '%' . $word . '%')
            ->take($this->MaxCount)
            ->pluck('uid')->toArray();
        $text1List = Search_grModel::where('text1', 'LIKE', '%' . $word . '%')
            ->take($this->MaxCount)
            ->pluck('uid')->toArray();

        $outlist = $this->toArraygr($titleList);
        $newList = [];
        foreach ($text1List as $vo) {
            if (!in_array($vo, $titleList)) {
                $titleList[] = $vo;
                $newList[] = $vo;
            }
        }
        // print_r($newList);exit;
        $newout = $this->toArraygr($newList);
        $outlist = array_merge($outlist, $newout);
        return $outlist;
    }

    private function getfindHd($word)
    {
        $titleList = Search_hdModel::where('name', 'LIKE', '%' . $word . '%')
            ->take($this->MaxCount)
            ->pluck('tid')->toArray();
        $text1List = Search_hdModel::where('text1', 'LIKE', '%' . $word . '%')
            ->take($this->MaxCount)
            ->pluck('tid')->toArray();

        $outlist = $this->toArrayhd($titleList);
        $newList = [];
        foreach ($text1List as $vo) {
            if (!in_array($vo, $titleList)) {
                $titleList[] = $vo;
                $newList[] = $vo;
            }
        }
        // print_r($newList);exit;
        $newout = $this->toArrayhd($newList);
        $outlist = array_merge($outlist, $newout);
        return $outlist;
    }


    private function getfindGw($word)
    {
        $titleList = Search_gwModel::where('name', 'LIKE', '%' . $word . '%')
            ->take($this->MaxCount)
            ->pluck('tid')->toArray();
        $text1List = Search_gwModel::where('text1', 'LIKE', '%' . $word . '%')
            ->take($this->MaxCount)
            ->pluck('tid')->toArray();

        $outlist = $this->toArraygw($titleList);
        $newList = [];
        foreach ($text1List as $vo) {
            if (!in_array($vo, $titleList)) {
                $titleList[] = $vo;
                $newList[] = $vo;
            }
        }
        // print_r($newList);exit;
        $newout = $this->toArraygw($newList);
        $outlist = array_merge($outlist, $newout);
        return $outlist;
    }

    private function toArraygs_gc($newList)
    {
        //print_r($newList);
        exit("逻辑修改,这里弃用1");
        $model_list = CompanyModel::wherein('id', $newList)
            ->select([
                'uid', 'com_name', 'detail', 'id'
            ])->get();
        $list = [];
        foreach ($model_list as $vo) {
            $user = UserModel::getinfo($vo['uid']);

            $list[] = [
                'uid' => $vo['uid'],
                'user_name' => $user['name'],
                'user_head' => $user['head'],
                'com_name' => $vo['com_name'],
                'detail' => Fun::shenglue($vo['detail'], 64),
            ];
        }
        return $list;
    }

    /**
     * 个人简历
     */
    private function toArraygr($newList)
    {
        $list = [];
        foreach ($newList as $vo) {
            $user = UserModel::getinfo($vo);
            $list[] = [
                'uid' => $vo,
                'user_name' => $user['name'],
                'user_head' => $user['head'],
                'phone' => $user['phone'],
                'sex' => $user['sex']
            ];
        }
        return $list;

    }

    /**
     * 货单
     */
    private function toArrayhd($newList)
    {
        $list = [];
        foreach ($newList as $vo) {
            $one = OrderBaleModel::where('id', $vo)
                ->select([
                    'id',
                    'name',
                    'img',
                    'detail',
                    'is_rob',
                    //    'bond',
                    'period'
                ])
                ->first()->toArray();
            $one['period'] = Fun::date($one['period'], false);
            $list[] = $one;
        }
        return $list;
    }

    private function toArraygw($newList)
    {
        $modellist = JobsCompanysModel::wherein('id', $newList)
            ->get();
        //->toArray();
        $list = [];
        foreach ($modellist as $vo) {
            $user = UserModel::getinfo($vo->cid);
            $list[] = [
                'uid' => $vo->cid,
                'user_name' => $user['name'],
                'user_head' => $user['head'],
                'job' => JobModel::getName($vo->job),
                'company_name' => $vo->company_name,
                'skill' => $vo->skill,
                'address' => $vo->address,
                'emolument' => $vo->emolument,
                'id' => $vo->id
            ];
        }
        return $list;
    }


    /**
     * 创建缓存
     */
    public function createCache()
    {

        $this->chuliGs();
        $this->chuliGc();
        $this->chuliGr();
        $this->chuliHd();
        $this->chuligw();
    }


    /**
     * 删除搜索缓存数据
     */
    public function delData()
    {
        Search_gsModel::where([])->delete();
        Search_gcModel::where([])->delete();
        Search_grModel::where([])->delete();
    }

    /**
     * 处理公司类消息
     */
    public function chuliGs()
    {
        Search_gsModel::where([])->delete();
        UserGongsiModel::where([
            // 'type'=>\App\Models\Admin\CompanyModel::type_gongsi,
            'visible' => 1
        ])
            ->chunkById(100, function ($list) {
                foreach ($list as $vo) {
                    // echo $user->id."\t".$user->name;echo "\r\n";
                    $new = new Search_gsModel;
                    $new->name = $vo->com_name;
                    $new->uid = $vo->uid;
                    $new->tid = $vo->id;
                    $new->text1 = $vo->legal_name . "\t"
                        . $vo->legal_mobile
                        . $vo->com_tel
                        . $vo->com_fax
                        . \App\Models\AreaModel::getMergerName($vo->com_address)
                        . \App\Models\Admin\CategoryModel::getName($vo->out_type);
                    $new->text2 = $vo->detail;
                    $new->save();
                }
            });
    }

    /**
     * 处理工厂类消息
     */
    public function chuliGc()
    {
        Search_gcModel::where([])->delete();
        UsergongchangModel::where([

            'visible' => 1
        ])
            ->chunkById(100, function ($list) {
                foreach ($list as $vo) {
                    // echo $user->id."\t".$user->name;echo "\r\n";
                    $new = new Search_gcModel;
                    $new->name = $vo->com_name;
                    $new->uid = $vo->uid;
                    $new->tid = $vo->id;
                    $new->text1 = $vo->legal_name . "\t"
                        . $vo->legal_mobile
                        . $vo->com_tel
                        . $vo->com_fax
                        . \App\Models\AreaModel::getMergerName($vo->com_address)
                        . \App\Models\Admin\CategoryModel::getName($vo->out_type);
                    $new->text2 = $vo->detail;
                    $new->save();
                }
            });
    }

    /**
     * 处理个人资料类消息
     */
    public function chuliGr()
    {
        Search_grModel::where([])->delete();
        UserStaffModel::where([
            //  'type'=>\App\Models\Admin\CompanyModel::type_gongchang,
            'visible' => 1
        ])
            ->chunkById(100, function ($list) {
                foreach ($list as $vo) {
                    //  print_r($list);exit;
                    // $usersOptions=StaffOptionModel::where('uid',$vo->uid)->first();
                    $user = UserModel::getinfo($vo->uid);
                    $new = new Search_grModel;
                    $new->name = $vo->realname;
                    $new->uid = $vo->uid;
                    $new->tid = $vo->id;
                    $new->sex = $vo->sex;
                    $new->text1 = $vo->job_str . "\t"
                        . $vo->household_address
                        . $vo->residential_address
                        . $vo->nationality
                        . $vo->realname;
                    if ($user) {
                        /// $new->text1.=$user['name'].$user['phone'];
                        $new->name = $user['name'] . $user['phone'];
                    }
                    $new->save();
                }
            });
    }

    /**
     * 处理货单类消息
     */
    public function chuliHd()
    {
        Search_hdModel::where([])->delete();
        OrderBaleModel::where([
            //  'type'=>\App\Models\Admin\CompanyModel::type_gongchang,
            'visible' => 1
        ])
            ->chunkById(100, function ($list) {
                foreach ($list as $vo) {
                    // $usersOptions=StaffOptionModel::where('uid',$vo->uid)->first();
                    $user = UserModel::getinfo($vo->uid);
                    $new = new Search_hdModel;
                    $new->name = $vo->name . CategoryModel::getName($vo->cate);
                    $new->uid = $vo->uid;
                    $new->tid = $vo->id;


                    $new->text1 = $vo->styleNo . "\t"   //款号
                        . $vo->styleName //款式名称
                        . $vo->scence    //适用场景
                        . $vo->material  //材质
                        . $vo->tech  ///工艺要求
                        ///
                        ///
                        . $vo->outTypeStr  ///货单分类集合
                        . $vo->orderType  ///产品类型，json：name 产品名称
                        . $vo->style ///产品风格名称数组，用||隔开
                        . $vo->design    ///产品款式名称数组，用||隔开
                        . $vo->detail    ///货单描述


                    ;
                    if ($user) {
                        /// $new->text1.=$user['name'].$user['phone'];
                        $new->name .= $user['name'] . $user['phone'];
                    }
                    $new->save();
                }
            });
    }


    /**
     * 处理岗位信息
     */
    public function chuligw()
    {
        Search_gwModel::where([])->delete();
        JobsCompanysModel::where([
            'status' => JobsCompanysModel::status_fabuzhong,
            'del' => 0
        ])
            ->chunkById(100, function ($list) {
                foreach ($list as $vo) {
                    $user = UserModel::getinfo($vo->cid);
                    $new = new Search_gwModel;
                    $new->name = $vo->company_name . JobModel::getName($vo->job);
                    $new->uid = $vo->cid;
                    $new->tid = $vo->id;

                    $new->text1 = $vo->address
                        . $vo->detail
                        . $vo->content
                        . $vo->skill;
                    if ($user) {
                        $new->text1 .= $user['name'] . $user['phone'];
                    }
                    $new->save();
                }
            });
    }
}